﻿using lwzlz.Application.System;
using lwzlz.Application.System.Dto;
using lwzlz.Common;
using lwzlz.Web.Areas.SysAdmin.Models;
using lzwlz.Web;
using System;
using System.Text;
using System.Web.Mvc;

namespace lwzlz.Web.Areas.Study.Controllers
{
    public class LoginController : BaseController
    {
        #region 界面
        /// <summary>
        /// 密码登录界面
        /// </summary>
        /// <returns></returns>
        public ActionResult PassWordLogin()
        {
            return View();
        }

        /// <summary>
        /// 验证码登录界面
        /// </summary>
        /// <returns></returns>
        public ActionResult MsgCodeLogin()
        {
            return View();
        }

        /// <summary>
        /// 忘记密码界面
        /// </summary>
        /// <returns></returns>
        public ActionResult ForgetPassWord()
        {
            return View();
        }

        #endregion

        #region 接口
        /// <summary>
        /// 密码登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult PassWordLogin(string userName, string passWord)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var studentService = new StudentService();
                var result = studentService.Login(userName, passWord, out StudentLogin model);

                if (result.Success)
                {
                    studentService.UpdateLoginTime(model.Id);//更新登录时间

                    int KeepHours = 720;//默认过期时间（小时）

                    // 写入用户身份验证票证
                    StudyStudentLogin.SignIn(model, KeepHours * 60);

                    var url = ZCookies.GetCookies("historyUrl");
                    if (url != null)
                    {
                        ZCookies.DelCookie("historyUrl");
                    }
                    else
                    {
                        url = Url.RouteUrl(new { area = "Study", controller = "Font", action = "Detail" });
                    }

                    response.Data = url;
                    response.Success = true;
                    response.Message = "登录成功";
                }
                else
                {
                    response.Success = false;
                    response.Message = result.Message;
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 验证码登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="msgCode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult MsgCodeLogin(string userName, string msgCode)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                //验证手机验证码
                object Server_Code = Session["login_phone_" + userName + "_code"];

                if (Server_Code == null || Server_Code.ToString() != msgCode)
                {
                    response.Message = "验证码错误";
                }
                else
                {
                    var studentService = new StudentService();
                    var entity = studentService.GetMember(userName);

                    if (entity != null)
                    {
                        var model = new StudentLogin()
                        {
                            Id = entity.Id,
                            UserName = entity.UserName,
                            RealName = entity.RealName,
                            Phone = entity.Phone,
                            Status = entity.Status
                        };

                        studentService.UpdateLoginTime(entity.Id);//更新登录时间

                        int KeepHours = 720;//默认过期时间（小时）

                        // 写入用户身份验证票证
                        StudyStudentLogin.SignIn(model, KeepHours * 60);

                        var url = ZCookies.GetCookies("historyUrl");
                        if (url != null)
                        {
                            ZCookies.DelCookie("historyUrl");
                        }
                        else
                        {
                            url = Url.RouteUrl(new { area = "Study", controller = "Font", action = "Detail" });
                        }

                        response.Data = url;
                        response.Success = true;
                        response.Message = "登录成功";
                    }
                    else
                    {
                        response.Success = false;
                        response.Message = "会员不存在";
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="msgCode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ResetPassWord(string userName, string passWord, string msgCode)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                //验证手机验证码
                object Server_Code = Session["reset_phone_" + userName + "_code"];

                if (Server_Code == null || Server_Code.ToString() != msgCode)
                {
                    response.Message = "验证码错误";
                }
                else
                {
                    var studentService = new StudentService();
                    var entity = studentService.GetMember(userName);

                    if (entity != null)
                    {
                        entity.PassWord = new Common.Symmetric().Encrypto(passWord);
                        entity.LastModificationTime = DateTime.Now;
                        studentService.Update(entity, null);

                        response.Data = Url.Action("PassWordLogin", "Login");
                        response.Success = true;
                        response.Message = "重置成功";
                    }
                    else
                    {
                        response.Success = false;
                        response.Message = "会员不存在";
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 创建随机数
        /// </summary>
        /// <param name="Length"></param>
        /// <returns></returns>
        private string GenerateRandomNumber(int Length)
        {
            char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            StringBuilder newRandom = new StringBuilder();
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(10)]);
            }
            return newRandom.ToString();
        }

        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="type">0-登录；1-重置密码</param>
        /// <returns></returns>
        public ActionResult SendSms(string phone, int type = 0)
        {
            ResponseModel response = new ResponseModel();
            response.Success = false;
            try
            {
                if (!ExistLoginInfo(phone))
                {
                    throw new Exception("账户不存在");
                }

                var MsgCode = GenerateRandomNumber(4);//创建随机数
                var text = "";
                var templateCode = "";
                switch (type)
                {
                    case 0:
                        text = "login_phone_" + phone + "_code";
                        templateCode = "SMS_205250005";
                        break;
                    case 1:
                        text = "reset_phone_" + phone + "_code";
                        templateCode = "SMS_205250002";
                        break;
                    default:
                        break;
                }

#if DEBUG
                Session[text] = MsgCode;
                Session.Timeout = 5;

                response.Success = true;
                response.Message = MsgCode;
                return Json(response);
#endif
                SMSHelp.PostMsg(phone, "{\"code\":\"" + MsgCode + "\"}", templateCode);

                Session[text] = MsgCode;
                Session.Timeout = 5;

                response.Success = true;
                response.Message = "验证码已发送,请注意查看。有效时间五分钟。";
            }
            catch (Exception ee)
            {
                response.Message = ee.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 是否存在登录账号
        /// </summary>
        /// <param name="phone"></param>
        private bool ExistLoginInfo(string phone)
        {
            var student = new StudentService().GetMember(phone, null);
            if (student != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
    }
}